import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
// import permission from './modules/permission'
import getterUsers from './getters'

// 购物车
import mutations from './mutations'
import actions from './action'

Vue.use(Vuex)

const state = {
  // 商品列表
  good_list: [{
      id: '1',
      name: '波士顿龙虾1',
      price: 9.9,
      src:'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=130857645,1241554531&fm=26&gp=0.jpg'
  }, {
      id: '2',
      name: '波士顿龙虾2',
      price: 12.8,
      src:'https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3093412350,1368292299&fm=26&gp=0.jpg'
  }, {
      id: '3',
      name: '波士顿龙虾3',
      price: 3.9,
      src:'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=253368937,3862058320&fm=26&gp=0.jpg'
  }, {
      id: '4',
      name: '波士顿龙虾4',
      price: 5.6,
      src:'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1694553089,3056659475&fm=26&gp=0.jpg'
  }],
  //添加到购物车的商品
  added:[
    {
      id: "1",
      num: 1
    },{
      id: "2",
      num: 1
    }
  ]
}

const getters = {

  //商品列表
  goodList : state =>{
      return state.good_list.map( item => {
          return {
              id : item.id,
              name : item.name,
              price : item.price.toFixed(2),
          }
      })
  } ,

  //购物车的列表
  cartProducts : state=>{
      return state.added.map(({id,num})=>{
          let product = state.good_list.find( item => item.id == id )
          // console.info('product',product)
          return {
              id : product.id,
              name : product.name,
              price : product.price.toFixed(2),
              num,
              total_num : (product.price*num).toFixed(2),
              src : product.src
          }
      })
  },

  //计算总价
  totalPrice:(state,getters)=>{
      let total = 0;
      getters.cartProducts.forEach( item => {
          total += item.price * item.num
      })
      return total.toFixed(2);
  },

  //计算总数量
  totalNum : (state,getters)=>{
      let total = 0;
      getters.cartProducts.forEach( item => {
          total += item.num
      })
      return total;
  },
}

const store = new Vuex.Store({
  modules: {
    user,
  },  
  getterUsers,
  state, //购物车
  actions, //购物车
	mutations, //购物车
  getters //购物车
})

export default store
